package zuoye5.第三题;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadRunnableTest implements Runnable{

    private String oldName;

    private String newName;

    public ThreadRunnableTest(String oldPath, String newPath) {
        this.oldName = oldPath;
        this.newName = newPath;
    }

    @Override
    public void run() {
        ThreadRunnableTest.copyFolder(oldName,newName);
    }

    public static void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            //旧文件对象
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                /*分割符加文件名F:\222
                比如说直接传这个文件夹，没有分隔符，那我所有的文件要加上分隔符
                如果有，就不用加
                 */
                if(oldPath.endsWith(File.separator)){
                    //分隔符加文件名F:\222
                    temp=new File(oldPath+file[i]);
                }
                else{
                    //不是以分隔符结尾，分隔符加文件名F:\222\222.txt
                    temp=new File(oldPath+File.separator+file[i]);
                }
                //如果是文件
                if(temp.isFile()){
                    //创建一个文件输入流
                    FileInputStream input = new FileInputStream(temp);
                    //创建一个文件输出流，位置对应旧文件
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    //F:\222\333，333就是F:\222下的子文件夹，继续递归，加上分隔符和文件命
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {
        // 1.创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadRunnableTest trt = new ThreadRunnableTest("F:\\222","F:\\444");
        Thread t1 = new Thread(trt);
        t1.start();
        // 2.向线程池中布置任务
        executorService.submit(trt);
        // 3.关闭线程池
        executorService.shutdown();



    }


}
